<?php

require_once dirname(__FILE__).'/../lib/productGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/productGeneratorHelper.class.php';

/**
 * product actions.
 *
 * @package    eel
 * @subpackage product
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class productActions extends autoProductActions
{
  public function executeClearFolder(sfWebRequest $request) 
  {
  	$temp_folder = sfConfig::get('sf_upload_dir')."/_temp/";
  	$small_folder = sfConfig::get('sf_upload_dir')."/_temp/_small/";
  	$middle_folder = sfConfig::get('sf_upload_dir')."/_temp/_middle/";
  	
  	$arr_temp = array($temp_folder,$small_folder,$middle_folder);
	$this->arr_temp = $arr_temp;
	
    foreach($arr_temp as $temp_path)
  	{
		$d=@dir($temp_path);
		while(false !== ($e= $d->read())) 
		{
			if(is_file($temp_path.$e))
			{
				unlink($temp_path.$e);
			}
		}
		$d->close();
  	}	
  }
  
  
  public function executeEdit(sfWebRequest $request)
  {
	$this->categoryList = CategoryTable::getCategoryListOrderByName();
	$this->productTypeList = ProductTypeTable::getProductTypeListOrderByName();
  	
  	if($request->getMethod() == 'POST')
  	{
  		$product_name = $request->getParameter('product_name');
  		
  		$product = ProductTable::getInstance()->find($request->getParameter('product_id'));
  		$product->setName($product_name);
  		$product->save();

        $this->getUser()->setFlash('notice', 'The item was updated successfully.');
        $this->redirect(array('sf_route' => 'product_edit', 'sf_subject' => $product));    	
  	}
  	else
  	{
    	$this->product = $this->getRoute()->getObject();
    	$this->availableDownloadTypes = array();
    	$mapings = ProductTypeHasDownloadTypeTable::getProductTypeHasDownloadTypeListByProductTypeId($this->product->getProductType()->getId());
  		foreach ($mapings as $maping)
  		{
  			$this->availableDownloadTypes[] = $maping->getDownloadType();
  		}
  		$arr_temp = DownloadLinkTable::getDownloadLinkByProductId($this->product->getId());
  		$arr_links = array();
  		$ojb_product_picture=null;
  		foreach ($arr_temp as $item)
  		{
  			if($item->getDownloadType()->getName() == "Product picture" && 
  			   strpos($item->getOriginalName(),"small_") !== false)
  			{
  				$ojb_product_picture = $item;
  				continue;
  			}
  			$arr_links[] = $item;
  		}
  		if($ojb_product_picture != null)
  		{
  			array_push($arr_links,$ojb_product_picture);
  		}
  		
  		$this->downloadLinks = $arr_links;
  	}
  }
  
  public function executeGetCategoryListByParentId(sfWebRequest $request)
  {
  	$temp_parent_id = $request->getParameter("parent_id");
  	$temp_parent_array = explode("_",$temp_parent_id);
  	$parent_id = $temp_parent_array[1];
  	$level = $request->getParameter("level");
  	$category_list = CategoryTable::getCategoryListByParentId($parent_id);
  	
  	if(count($category_list)<1)
  	{
  		return $this->renderText("");
  	}
  	$level++;
  	$re_string = '<select id="product_category_id_'.$level.'" name="product_category_ids[]" onchange="getSubCategory('.$level.')">';
  	$re_string .= '<option value="">Select</option>';
  	foreach ($category_list as $category)
  	{
  		$re_string .= "<option value='".$level."_".$category->getId()."'>".$category->getName()."</option>";
  	}
  	$re_string .= "</select>";
  	return $this->renderText($re_string);
  }
  	
  public function executeNew(sfWebRequest $request)
  {
  	if($request->getMethod() == 'POST')
  	{
  		//category
  		$arr_category_temp = $request->getParameter('product_category_ids');
		$arr_category = array();
		foreach($arr_category_temp as $category_temp)
		{
			if($category_temp != "")
			{
				$temp = explode("_",$category_temp);
				$arr_category[$temp[1]] = $temp[0];
			}
		}  		
  		$category_id = 0;
  		$category_level = 0;
  		foreach ($arr_category as $k=>$v)
  		{
  			if($v>=$category_level)
  			{
  				$category_level=$v;
  				$category_id=$k;
  			}
  		}
  		//product type
  		$product_product_type_id = $request->getParameter('product_product_type_id');
  		
  		//for images and box rendering
  		if($request->getParameter("hid_is_special") == "1")
  		{
  			//save the uploaded files
	  		$files = $request->getParameter('uploadedPictures');
			if($files != null)
			{
				$current_timestamp="";
				$arr_product_temp = array();
				foreach($files as $file)
				{
					$arr_tmp = explode("#",$file);
					$file_name = $arr_tmp[0];
					$download_type_id = $arr_tmp[1];
					$picture_type = $arr_tmp[2];
					switch ($download_type_id)
					{
						case "special_original":
							$download_type_id = DownloadTypeTable::getHighResDownloadTypeId();
							break;
						case "special_small":
							$download_type_id = DownloadTypeTable::getProductpictureDownloadTypeId();
							break;
						case "special_middle":
							$download_type_id = DownloadTypeTable::getLowResDownloadTypeId();
							break;
						default:
							break;
					}
					
					if(strpos($file_name,"small_") === false)
					{
						$check_name = $file_name;
					}
					else
					{
						$check_name = substr($file_name,6);
					}
					
					if($current_timestamp != $check_name)
					{
						//save the product
						$arr_original_name = explode(".",$file_name);
						$auto_name = $arr_original_name[0];
				  		$product = new Product();
				  		$product->setCategoryId($category_id);
				  		$product->setProductTypeId($product_product_type_id);
				  		$product->setName($auto_name);
				  		$product->save();
				  		
				  		$arr_product_temp[$file_name] = $product;
					}
					else
					{
						$product = $arr_product_temp[$check_name];
					}
					$current_timestamp = $check_name;
					
					//move the uploaded pictures
					$file_url = "";
					if($picture_type == "original")
					{
						$tmp_file = sfConfig::get('sf_upload_dir')."/_temp/".$file_name;
						$tar_file = sfConfig::get('sf_web_dir')."/High-Res/".$file_name;
						$file_url = "/High-Res/".$file_name;
					}
					else if($picture_type == "middle")
					{
						$tmp_file = sfConfig::get('sf_upload_dir')."/_temp/_middle/".$file_name;
						$tar_file = sfConfig::get('sf_web_dir')."/Low-Res/".$file_name;	
						$file_url = "/Low-Res/".$file_name;					
					}
					else if($picture_type == "small")
					{
						$tmp_file = sfConfig::get('sf_upload_dir')."/_temp/_small/".$file_name;
						$tar_file = sfConfig::get('sf_web_dir')."/Product picture/".$file_name;	
						$file_url = "/Product picture/".$file_name;						
					}
					else
					{
						die("Application error,contact the developer");
					}
					copy($tmp_file,$tar_file);
					unlink($tmp_file);
					
					//save downloadLink
					$download = new DownloadLink();
					$download->setDownloadTypeId($download_type_id);
					$download->setFileName($file_url);
					$download->setOriginalName($file_name);
					$download->setProductId($product->getId());
					$download->save();
				}
			}  
			
			$this->getUser()->setFlash('notice', 'These items were created successfully.');
			$this->redirect('product/new'); 
  		}
  		else
  		{
	  		$product_name = $request->getParameter('product_name');
	  		$product = new Product();
	  		$product->setCategoryId($category_id);
	  		$product->setProductTypeId($product_product_type_id);
	  		$product->setName($product_name);
	  		$product->save();
	  		
	  	  	//save the uploaded files
	  		$files = $request->getParameter('uploadedPictures');
			if($files != null)
			{
				foreach($files as $file)
				{
					$arr_tmp = explode("#",$file);
					$file_name = $arr_tmp[0];
					$download_type_id = $arr_tmp[1];
					$download_type_name = DownloadTypeTable::getDownloadTypeNameById($download_type_id);
					$picture_type = $arr_tmp[2];
					
					//move the uploaded pictures
					$file_url = "";
					if($picture_type == "original")
					{
						$tmp_file = sfConfig::get('sf_upload_dir')."/_temp/".$file_name;
					}
					else if($picture_type == "small")
					{
						$tmp_file = sfConfig::get('sf_upload_dir')."/_temp/_small/".$file_name;
					}
					else
					{
						die("Application error,contact the developer");
					}
					$tar_file = sfConfig::get('sf_web_dir')."/".$download_type_name."/".$file_name;
					$file_url = "/".$download_type_name."/".$file_name;
					copy($tmp_file,$tar_file);
					unlink($tmp_file);
					
					//save downloadLink
					$download = new DownloadLink();
					$download->setDownloadTypeId($download_type_id);
					$download->setFileName($file_url);
					$download->setOriginalName($file_name);
					$download->setProductId($product->getId());
					$download->save();
				}
			}  
	
	  		$this->getUser()->setFlash('notice', 'The item was created successfully.');
			if($request->hasParameter('_save_and_add'))
			{
	        	$this->redirect('product/new'); 	
			}
	  		else
	  		{
	        	$this->redirect(array('sf_route' => 'product_edit', 'sf_subject' => $product));  	
	  		}	  		
  		}	
  	}
  	else
  	{
		$this->categoryList = CategoryTable::getTopCategoryListOrderByName();
		$this->productTypeList = ProductTypeTable::getProductTypeListOrderByName();
  	}
  }	
  
  public function executeGetDownloadTypeByProductTypeId(sfWebRequest $request)
  {
	$product_type_id = $request->getParameter('product_type_id');
	$mapings = ProductTypeHasDownloadTypeTable::getProductTypeHasDownloadTypeListByProductTypeId($product_type_id);
	
	$str_re = "";
	foreach($mapings as $maping)
	{
		$str_re .= '<option value="'.$maping->getDownloadType()->getId().'">'.$maping->getDownloadType()->getName().'</option>';
	}
	
	return $this->renderText($str_re);
  }
  
  public function executeDeleteFileByFileId(sfWebRequest $request)
  {
	$file_id = $request->getParameter('file_id');
	$downloadLink = DownloadLinkTable::getInstance()->find($file_id);
	if($downloadLink != null)
	{
		$downloadLink->delete();
	}
	
	return $this->renderText("SUCCESS");
  }
  
  protected function buildQuery()
  {
    $query = parent::buildQuery();
    $query->orderBy("updated_at desc");
    
    return $query;
  }  
    
}
